package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@Configuration
@Order(1)
public class MyGlobalFilter implements GlobalFilter {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();

        System.out.println("请求接口："+url);

        if(url.contains("/HouseLogin") || url.contains("/CustomerLogin")){
            System.out.println("登录白名单");
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        if (token==null){
            System.out.println("token不存在:"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer custId = body.get("custId", Integer.class);
        Integer houseId = body.get("houseId", Integer.class);
        String redisKey="token-";
        String redistoken=null;
        if (custId==null){
           redisKey=redisKey+houseId;
        }else {
            redisKey=redisKey+custId;
        }
        redistoken = redisTemplate.opsForValue().get(redisKey);
        if (redistoken==null){
            System.out.println("token过期:"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        if (!token.equals(redistoken)){
            System.out.println("token不一致:"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        System.out.println("token验证通过:"+url);
        redisTemplate.expire(redisKey,5, TimeUnit.MINUTES);



        return chain.filter(exchange);
    }
}
